package com.trs.screen.demo;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    @BindView(R.id.tv_px)
    TextView pxTextView;
    @BindView(R.id.tv_dp)
    TextView dpTextView;
    @BindView(R.id.tv_density)
    TextView densityTextView;

    float density;
    DpiUtil dpiUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        init();
    }

    private void init() {
        ButterKnife.bind(this);
        density = getResources().getDisplayMetrics().density;
        dpiUtil = new DpiUtil(density);
        densityTextView.setText(String.format(Locale.getDefault(), "%.2f", density));
    }


    @OnClick({R.id.btn_transit, R.id.btn_transit_reverse})
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.btn_transit:
                px2dp();
                break;
            case R.id.btn_transit_reverse:
                dp2px();
                break;
        }
    }

    private void dp2px() {
        String dpString = dpTextView.getText().toString();
        if (dpString.isEmpty()) {
            Toast.makeText(this, "请输入 dp", Toast.LENGTH_SHORT).show();
            return;
        }
        float dp = Float.parseFloat(dpString);
        float px = dpiUtil.dip2px(dp);
        pxTextView.setText(String.format(Locale.getDefault(), "%.2f", px));
    }

    private void px2dp() {
        String pxString = pxTextView.getText().toString();
        if (pxString.isEmpty()) {
            Toast.makeText(this, "请输入 px", Toast.LENGTH_SHORT).show();
            return;
        }
        float px = Float.parseFloat(pxString);
        float dp = dpiUtil.px2dip(px);
        dpTextView.setText(String.format(Locale.getDefault(), "%.2f", dp));
    }
}
